import {buy, info, status,products ,pay} from '../services/seckill'
import moment from 'moment'
import {routerRedux } from 'dva/router';
import u from 'updeep'

export default {

	namespace: 'seckill',

	state: {
		product: {
			discountPrice: '¥ 100',
			originalPrice: '¥ 389',
			title: "秒杀前30名低至60元",
			btnTitle: '今天13:00开抢',
			startDate: new moment().format('X'),
			endDate: moment().add(3, 'h').format('X')
		},
		seckillInfo:{},
		status:{
			isRead: false,
			orderId: null,
			userId:"",
			timestamp:0,
			requestId:"",
			isSuccess:"exist",
		},
		allowShopping: false,
		btnDisable: true,
    shouldWaiting: true,
		products:null
	},

	subscriptions: {
		setup({dispatch, history}) {
			return history.listen(({pathname, query}) => {
				if (pathname === '/seckill') {
					dispatch({type: 'productInfo', payload: query});
				}
			});
		},
	},

	effects: {
	  *myOrders(payload, {call, put, update, select}){
      yield put(routerRedux.push({
        pathname: '/myOrders',
        query: {
          id: payload.id,
        }
      }));
    },
		*buy(payload, {call, put, update, select}) {  // eslint-disable-line
      let {url,endTime} = yield select (state => state.seckill.seckillInfo)
			const result = yield call(buy.bind(null, url,true))
			var data;
			if(result.err && result.err.status == 404){//已结束
				yield put({
					type: 'update',
					payload: {
						seckillInfo:{
							currentTime: endTime + 1,
						}
					}
				});
				return
			}

			if(result ) data = result.data

			if (data) {
				const queuing = data.seckillStatus === "queuing" ? true : false
				// console.log("data.payload:"+data.payload)
				const timestamp = result.ctimestamp
				//console.log("秒杀时间:"+timestamp)
				yield put({
					type: 'update',
					payload: {
						state: {
							status: data.payload,
							queuing,
              seckillStatus: data.seckillStatus
						},
						status:{
							requestId:data.requestId,
							timestamp
						}
					}
				});
				console.log("status == end?"+data.seckillStatus == 'end')
				if(data.seckillStatus == 'end'){
					yield put({
						type: 'update',
							payload: {
								seckillInfo:{
									currentTime: endTime + 1,
								}
							}
					});
					return
				}
				yield put(routerRedux.push({
          pathname: '/waiting',
          query: {
            id: payload.id,
            requestId: data.requestId
          }
        }));
			}
		},
		*products({payload},{call,put}){

			const {data} = yield call(products.bind(null))
			//console.log(JSON.stringify(data.payload))
			if(data && data.payload[0].id){
				yield put({
					type: 'update',
					payload:{
						products:data.payload
					}
				})
				if(payload.cb) payload.cb(data.payload[0].id);
			}

		},
		*productInfo({payload}, {call, put}){

      try{
        if (window.location.href.indexOf('/seckill') > -1) {
          yield put({
            type: 'update',
            payload: {
              seckillInfo: {}
            }
          });
        }

        const {data,err} = yield call(info.bind(null, payload.id))

				if(err&&err.status==404) alert('商品已空')

        if (data && data.payload) {
          const  {currentTime,productInfo} = data.payload;

          console.log('当前时间', currentTime.toString().substr(5))

          const seckillInfo = {currentTime,...productInfo}
          yield put({
            type: 'update',
            payload: {
              seckillInfo
            }
          });
        }
      }catch (e) {
        console.warn(e)
      }
		},
		*allowSeckill({payload}, {select,call, put}) {  // eslint-disable-line
			if(!payload.startTime) return;
			const seckill = yield select (state => state.seckill.seckillInfo)
			const seckillInfo = {...seckill}

			seckillInfo.startTime = payload.startTime
			seckillInfo.currentTime = payload.currentTime
			yield put({type: 'update', payload:{seckillInfo}});
		},
		*continueShopping({payload}, {put}) {  // eslint-disable-line
			yield put(routerRedux.goBack());
		},
    *status(payload, {call, put, select}) {  // eslint-disable-line
      const {data} = yield call(status.bind(null, payload.id,payload.requestId))
     // console.log(data)
      if(data && data.timestamp){
				const status = yield select (state => state.seckill.status)
				// console.log(data.timestamp+"&"+status.timestamp)
        // let se = !status.timestamp&&!status.requestId.length,
        //     ts = status.timestamp < data.timestamp && status.requestId === data.requestId;
        if( payload.requestId === encodeURIComponent(data.requestId)){
					console.log("秒到了")
					yield put({
						type: 'update',
						payload: {
							status:data
						}
					});
					if (data.isSuccess == "fail") {//失败
						console.log("jump")
						clearInterval(payload.timer)
						yield put(routerRedux.replace({
              pathname:'/fail',
              query: {
                id: payload.id,
                message:data.message
            }}));

					}else if(data.isSuccess){//已存在
						console.log("jump")
						clearInterval(payload.timer);
						yield put(routerRedux.replace({
              pathname: '/pay',
              query: {
                id: payload.id,
                orderId: data.orderId,
                message: data.message,
                ablePay: "true"
              }}))
					}
					return
				}
				console.log("the same")
			}
    },
    *pay(payload, {call, put, select}){
	   // console.log(payload)
      const {data} = yield call( pay.bind(null, payload.orderId ,payload.id))
      // console.log(data)
      let message = data? data.message: "订单支付失败";
      yield put(routerRedux.replace({
        pathname: '/pay',
        query: {
          id: payload.id,
          orderId: payload.orderId,
          ablePay: 'false',
          message:message
        }}
      ));


    }
	},

	reducers: {
		update(state, action) {
			// let result;
			// if(action.payload.seckillInfo){
			//   result = u(action.payload, state)
			// }else{
			// 	result = {...state, ...action.payload}
			// }
			const result = u(action.payload, state)
			return result;
		}
	}

};
